package com.huiying.cameramjpeg;

import android.text.TextUtils;

import com.fvision.camera.bean.DevFileName;
import com.fvision.camera.manager.DevFileNameManager;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zoulequan on 2018/5/28.
 */

public class SearchUSB1 {

    public String searchUsbPath() {
        String searchPath = null;
        List<String> paths = getMountPathList();
        if (paths != null && paths.size() > 0) {
            for (String path : paths) {
                searchPath = searchDir(path);
                if (!TextUtils.isEmpty(searchPath)) {
                    break;
                }
            }
        }
        if (TextUtils.isEmpty(searchPath)) {
            searchPath = searchDir("/storage/");
        }
        if (TextUtils.isEmpty(searchPath)) {
            searchPath = searchDir("/mnt/");
        }
        if (TextUtils.isEmpty(searchPath)) {
            searchPath = searchDir("/UsbStorage/");
        }
        return searchPath;
    }

    public boolean isInsertDevice() {
        String path = searchUsbPath();
        return !(path == null || path.equals(""));
    }

    /**
     * 递归搜索文件
     * @param path
     * @return
     */
    public String searchDir(String path) {
        if (path == null) {
            return null;
        }
        String searchPath = null;
        File file = new File(path);
        if (file == null) {
            return null;
        }
        File[] files = file.listFiles();

        if (files != null && files.length > 0) {
            for (File f : files) {
                if (f.isFile()) {
                    for (DevFileName dev : DevFileNameManager.getInstance().getDevList()) {
                        if (f.getName().equals(dev.getPreView())) {
                            searchPath = f.getAbsolutePath();
                            DevFileNameManager.getInstance().setCurrentDev(dev);
                            return searchPath;
                        }
                    }
                } else if (f.isDirectory()) {
                    String abspath = f.getAbsolutePath();
                    if (abspath.contains("sdcard")) {
                        if (f.listFiles() != null && f.listFiles().length > 10) {
                            return null;
                        }
                    }
                    String path1 = searchDir(f.getAbsolutePath());
                    if (!TextUtils.isEmpty(path1)) {
                        return path1;
                    }

                }
            }
        }
        return searchPath;
    }

//    public String getFilePath(String path) {
//        File file = new File(path);
//        File[] files = file.listFiles();
//        if (files != null && file.length() > 0)
//            for (File f : files) {
//                if (f.isFile()) {
//                    for (DevFileName dev : DevFileNameManager.getInstance().getDevList()) {
//                        if (f.getName().equals(dev.getPreView())) {
//                            return f.getAbsolutePath();
//                        }
//                    }
//                } else if (f.isDirectory()) {
//                    String abspath = f.getAbsolutePath();
//                    if (!abspath.contains("sdcard")) {
//                        Log.d("zoulequan", "searchDir " + abspath);
//                        return getFilePath(f.getAbsolutePath());
//                    }
//                }
//            }
//        return null;
//    }

    /**
     * 获取所有存储卡挂载路径
     *
     * @return
     */
    public static List<String> getMountPathList() {
        List<String> pathList = new ArrayList<String>();
        final String cmd = "cat /proc/mounts";
        Runtime run = Runtime.getRuntime();//取得当前JVM的运行时环境
        try {
            Process p = run.exec(cmd);//执行命令
            BufferedInputStream inputStream = new BufferedInputStream(p.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 获得命令执行后在控制台的输出信息
                //输出信息内容：  /data/media /storage/emulated/0 sdcardfs rw,nosuid,nodev,relatime,uid=1023,gid=1023 0 0
               // Log.e("getmoutpathlis", line);
                String[] temp = TextUtils.split(line, " ");
                //分析内容可看出第二个空格后面是路径
                String result = temp[1];
                if (result.toLowerCase().contains("udisk") || result.toLowerCase().contains("usb")) {
                    File file = new File(result);
                    //类型为目录、可读、可写，就算是一条挂载路径
                    if (file.isDirectory() && file.canRead() && file.canWrite()) {
                        pathList.add(result);
                    }
                }

                // 检查命令是否执行失败
                if (p.waitFor() != 0 && p.exitValue() == 1) {
                    // p.exitValue()==0表示正常结束，1：非正常结束
//                    Logger.e(命令执行失败!);
                }
            }
            bufferedReader.close();
            inputStream.close();
        } catch (Exception e) {
//            Logger.e(e.toString());
            e.printStackTrace();
            //命令执行异常，就添加默认的路径
            pathList.add("/storage");
        }
        return pathList;
    }
}
